import {Singleton, Injector} from "ts.di";
// import {NeteaseSMS} from "../../../NeteaseSMS/NeteaseSMS";
import {Connection} from "typeorm";
import {SMSSentInfo} from "./SMSSentInfo";
import {AliDayuSMS} from "../../AliDayuSMS/AliDayuSMS";
import {tr} from "../Core/Localization/Translator";
/**
 * Created by Weizehua on 2017/1/21.
 */
interface CaptchaSentInfo {
    success: boolean,
    captcha?: string,
    reason?: string;
}

@Singleton()
export class SMSService {
    constructor(private aliDayu: AliDayuSMS,
                private typeorm: Connection) {
    }

    async sendCaptcha(phone: string, availableMinutes: number = 3): Promise<CaptchaSentInfo> {
        let count = await this.typeorm.entityManager
            .createQueryBuilder(SMSSentInfo, 'info')
            .where('info.phone = :phone')
            .andWhere('info.sentDate > :date')
            .setParameters({
                phone: phone,
                date: (Number(new Date()) - 1000 * 60 * this.sentLimit.inMinutes)
            })
            .getCount();

        if (count >= this.sentLimit.count)
            return {success: false, reason: tr('Sent count of phone captcha reached limit!')};

        // return Injector.get(NeteaseSMS).requestSendCaptcha(phone);
        let captcha = await Injector.get(AliDayuSMS).sendCaptcha(phone, availableMinutes);

        let info = new SMSSentInfo();
        info.phone = phone;
        info.captcha = captcha;
        await this.typeorm.entityManager.persist(info);
        return {success: true, captcha: info.captcha};
    }

    async validateCaptcha(phone: string, captcha: string) {
        let info = await this.typeorm.entityManager
            .createQueryBuilder(SMSSentInfo, 'info')
            .where('info.phone = :phone', {phone: phone})
            .orderBy('info.sentDate', 'DESC')
            .getOne();
        return info && info.captcha === captcha;
    }

    private sentLimit = {
        count: 50,
        inMinutes: 10
    }
}
